package com.wedata.wegymer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.wedata.HttpUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 美团接口文档：
 * http://open.dianping.com/document/v2?docId=6000846&rootDocId=5000
 *
 */
public class 美团验券核销 {

    public static void main(String[] args) {
        String receipt_code = "8115266237";
        //prepare("ca013586f6efa4540af16a5e444f8769",receipt_code);
        //reverseconsume(receipt_code);
        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"8706084447","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1,"deal_marketprice":780,"mobile":"138****5446","product_type":null,"product_item_id":null,"biz_type":0,"payment_detail":[{"payment_detail_id":"4935971480375171693SWSZ50101","amount":1,"amount_type":10}],"receipt_info_map":null,"receiptEndDate":1701964799000}}
        //{"code":1008,"msg":"此券码已被验证，验证时间：2023-11-23 10:23:31，验证商户：WEGYMER健萌健身(万科梅溪郡店)","data":{"count":1,"receipt_code":"8115266237","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":null,"deal_price":null,"deal_marketprice":null,"mobile":"138****5446","product_type":null,"product_item_id":null,"biz_type":0,"payment_detail":[{"payment_detail_id":"4935971480375171693SWSZ50101","amount":1,"amount_type":10}],"receipt_info_map":null,"receiptEndDate":1701964799000}}
        //reverseconsume(receipt_code);
        //{"code":200,"msg":"success","data":[{"order_id":"4935971480375171693","receipt_code":"8706084447","app_shop_id":null,"open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","product_type":null,"product_item_id":null,"deal_price":1,"deal_marketprice":780,"mobile":"138****5446","biz_type":null,"payment_detail":null,"receiptEndDate":null,"disclose_mobile_no":null,"product_snapshot":null}]}
        //{"code":200,"msg":"success","data":[{"order_id":"4935971480375171693","receipt_code":"8115266237","app_shop_id":null,"open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","product_type":null,"product_item_id":null,"deal_price":1,"deal_marketprice":780,"mobile":"138****5446","biz_type":null,"payment_detail":null,"receiptEndDate":null,"disclose_mobile_no":null,"product_snapshot":null}]}
        prepare("50e5784028a4be6def50533d4e4f4191","4883381931");

    }
    public static void paymentshares() {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", "5728ff5933bdaf04" );
        //requestParam.put("timestamp", "2023-11-14 13:38:10");
        requestParam.put("timestamp", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");


        requestParam.put("session", "baf5e34257ec5afdcd3133d1d15c222f130be2a9");

        requestParam.put("order_id", "4935967745443642247");
        requestParam.put("type", "0");

        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", generateSign(requestParam, "632cfc8411c582ab8251417b25116d4a8a6f35a2", "MD5"));
        //构造form
        String url = "https://openapi.dianping.com/router/order/receipt/paymentshares?"+generateParams(requestParam);
        System.out.println(url);
        JSONObject jsonObject = HttpUtils.doGet(url);
        System.out.println(jsonObject);
    }


    //撤销核销
    public static void reverseconsume(String receipt_code) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", "5728ff5933bdaf04" );
        //requestParam.put("timestamp", "2023-11-14 13:38:10");
        requestParam.put("timestamp", "2023-11-14 13:39:10");
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        /*requestParam.put("open_shop_uuid", "c5ad397cc7ac17b253e5c2c20b0162fd");
        requestParam.put("receipt_code", "0332808512");*/
        //{"code":1012,"msg":"此团购券不可在本店消费，请让消费者打开购买App查看该订单详情页中的可适用商户。"}

        requestParam.put("open_shop_uuid", "ca013586f6efa4540af16a5e444f8769");
        //requestParam.put("receipt_code", "7395466112");
        requestParam.put("receipt_code", receipt_code);
        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        requestParam.put("session", "ab5d80236e1afb21e94cdacc64bf4ca4ffc6399e");

        requestParam.put("app_deal_id", "1192015505");
        requestParam.put("app_shop_account", "123456");
        requestParam.put("app_shop_accountname", "test123");

        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", generateSign(requestParam, "632cfc8411c582ab8251417b25116d4a8a6f35a2", "MD5"));
        //构造form
        JSONObject jsonObject = HttpUtils.sendPostByForm("https://openapi.dianping.com/router/tuangou/receipt/reverseconsume",generateParams(requestParam));
        System.out.println(jsonObject);
        //{"code":200,"msg":"验证成功","data":[{"biz_type":0,"deal_id":1192015505,"deal_marketprice":780.0,"deal_price":1.0,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","dealgroup_id":886005069,"disclose_mobile_no":0,"mobile":"155****3090","open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","order_id":"169986688975204150681536","payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"product_snapshot":"{\"skuDetailStructDTO\":\"{\\\"marketPrice\\\":\\\"780元\\\",\\\"mustGroups\\\":[{\\\"dealStructInfo\\\":[{\\\"copies\\\":\\\"1份\\\",\\\"price\\\":\\\"780元\\\",\\\"skuId\\\":0,\\\"title\\\":\\\"常规私教体验课\\\"}]}],\\\"price\\\":\\\"1元\\\",\\\"publishCategoryId\\\":1802,\\\"richText\\\":\\\"<p>温馨提示：</p><p></p><p>1、此卡仅限非健萌会员使用，且新用户只可购买1次；</p><p></p><p>2、购卡后需提前1天电话联系客服或点击在线咨询预约，客服会为您介绍使用流程；</p><p></p><p>3、如需预约其他时间，也可咨询客服帮您协调，并兑换后7天内使用。</p>\\\",\\\"title\\\":\\\"团购详情\\\"}\"}","receiptEndDate":1701187199000,"receipt_code":"7903583393"}]}
        //{"code":200,"msg":"success","data":[{"order_id":"4935971320683308031","receipt_code":"7903583393","open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090"}]}
        //{"code":200,"msg":"success","data":[{"order_id":"4935971320683308031","receipt_code":"7395466112","open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090"}]}
    }

    //核销
    public static void consume() {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", "5728ff5933bdaf04" );
        //requestParam.put("timestamp", "2023-11-14 13:38:10");
        requestParam.put("timestamp", "2023-11-14 13:39:10");
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        /*requestParam.put("open_shop_uuid", "c5ad397cc7ac17b253e5c2c20b0162fd");
        requestParam.put("receipt_code", "0332808512");*/
        //{"code":1012,"msg":"此团购券不可在本店消费，请让消费者打开购买App查看该订单详情页中的可适用商户。"}
        //{"code":200,"msg":"验证成功","data":[{"biz_type":0,"deal_id":1192015505,"deal_marketprice":780.0,"deal_price":1.0,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","dealgroup_id":886005069,"disclose_mobile_no":0,"mobile":"155****3090","open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","order_id":"169986688975204150681536","payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"product_snapshot":"{\"skuDetailStructDTO\":\"{\\\"marketPrice\\\":\\\"780元\\\",\\\"mustGroups\\\":[{\\\"dealStructInfo\\\":[{\\\"copies\\\":\\\"1份\\\",\\\"price\\\":\\\"780元\\\",\\\"skuId\\\":0,\\\"title\\\":\\\"常规私教体验课\\\"}]}],\\\"price\\\":\\\"1元\\\",\\\"publishCategoryId\\\":1802,\\\"richText\\\":\\\"<p>温馨提示：</p><p></p><p>1、此卡仅限非健萌会员使用，且新用户只可购买1次；</p><p></p><p>2、购卡后需提前1天电话联系客服或点击在线咨询预约，客服会为您介绍使用流程；</p><p></p><p>3、如需预约其他时间，也可咨询客服帮您协调，并兑换后7天内使用。</p>\\\",\\\"title\\\":\\\"团购详情\\\"}\"}","receiptEndDate":1701187199000,"receipt_code":"7395466112"}]}

        requestParam.put("open_shop_uuid", "ca013586f6efa4540af16a5e444f8769");
        requestParam.put("receipt_code", "7395466112");
        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        requestParam.put("session", "ab5d80236e1afb21e94cdacc64bf4ca4ffc6399e");

        requestParam.put("requestid", "disdr123");
        requestParam.put("count", "1");
        requestParam.put("app_shop_account", "123456");
        requestParam.put("app_shop_accountname", "test123");

        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", generateSign(requestParam, "632cfc8411c582ab8251417b25116d4a8a6f35a2", "MD5"));
        //构造form
        JSONObject jsonObject = HttpUtils.sendPostByForm("https://openapi.dianping.com/router/tuangou/receipt/consume",generateParams(requestParam));
        System.out.println(jsonObject);
        //{"code":200,"msg":"验证成功","data":[{"biz_type":0,"deal_id":1192015505,"deal_marketprice":780.0,"deal_price":1.0,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","dealgroup_id":886005069,"disclose_mobile_no":0,"mobile":"155****3090","open_shop_uuid":"ca013586f6efa4540af16a5e444f8769","order_id":"169986688975204150681536","payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"product_snapshot":"{\"skuDetailStructDTO\":\"{\\\"marketPrice\\\":\\\"780元\\\",\\\"mustGroups\\\":[{\\\"dealStructInfo\\\":[{\\\"copies\\\":\\\"1份\\\",\\\"price\\\":\\\"780元\\\",\\\"skuId\\\":0,\\\"title\\\":\\\"常规私教体验课\\\"}]}],\\\"price\\\":\\\"1元\\\",\\\"publishCategoryId\\\":1802,\\\"richText\\\":\\\"<p>温馨提示：</p><p></p><p>1、此卡仅限非健萌会员使用，且新用户只可购买1次；</p><p></p><p>2、购卡后需提前1天电话联系客服或点击在线咨询预约，客服会为您介绍使用流程；</p><p></p><p>3、如需预约其他时间，也可咨询客服帮您协调，并兑换后7天内使用。</p>\\\",\\\"title\\\":\\\"团购详情\\\"}\"}","receiptEndDate":1701187199000,"receipt_code":"7903583393"}]}
        //{"code":1132,"msg":"该券码已被撤销验证，平台为用户生成了新的券码，请引导用户重新进入订单详情页获取新的券码。"}
    }

    //核销校验
    public static void prepare(String open_shop_uuid, String receipt_code) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", "5728ff5933bdaf04" );
        //requestParam.put("timestamp", "2023-11-14 13:38:10");
        requestParam.put("timestamp", "2023-11-14 13:39:10");
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        /*requestParam.put("open_shop_uuid", "c5ad397cc7ac17b253e5c2c20b0162fd");
        requestParam.put("receipt_code", "0332808512");*/
        //{"code":1012,"msg":"此团购券不可在本店消费，请让消费者打开购买App查看该订单详情页中的可适用商户。"}

        /*requestParam.put("open_shop_uuid", "ca013586f6efa4540af16a5e444f8769");
        requestParam.put("receipt_code", "7903583393");*/
        requestParam.put("open_shop_uuid", open_shop_uuid);
        requestParam.put("receipt_code", receipt_code);
        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        //{"code":200,"msg":"验证校验通过","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"deal_title":"【双11限量】7天3节1对1周卡｜请提前1天预约","deal_price":1.0,"deal_marketprice":780.0,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        //{"code":1008,"msg":"此券码已被验证，验证时间：2023-11-14 15:25:06，验证商户：WEGYMER健萌健身(万科梅溪郡店)","data":{"count":1,"receipt_code":"7903583393","deal_id":1192015505,"dealgroup_id":886005069,"mobile":"155****3090","biz_type":0,"payment_detail":[{"payment_detail_id":"4935971320683308031CWTY50101","amount":1.00,"amount_type":10}],"receiptEndDate":1701187199000}}

        requestParam.put("session", "ab5d80236e1afb21e94cdacc64bf4ca4ffc6399e");
        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", generateSign(requestParam, "632cfc8411c582ab8251417b25116d4a8a6f35a2", "MD5"));
        //构造form
        JSONObject jsonObject = HttpUtils.sendPostByForm("https://openapi.dianping.com/router/tuangou/receipt/prepare",generateParams(requestParam));
        System.out.println(jsonObject);
        //发起post请求
        /*return Request Post("https://openapi.dianping.com/router/tuangou/receipt/prepare")
                .bodyForm(form.build())
                .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded","UTF-8").toString())
                .execute().returnContent().asString();*/
    }

    /**
     * 查询美团团购订单
     * @param open_shop_uuid
     * @param receipt_code
     */
    public static void queryOrder(String open_shop_uuid, String receipt_code) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", "5728ff5933bdaf04" );
        //requestParam.put("timestamp", "2023-11-14 13:38:10");
        requestParam.put("timestamp", "2023-11-14 13:39:10");
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");

        //requestParam.put("unified_order_id", open_shop_uuid);//统一订单ID（开放平台对外透出的订单号）
        requestParam.put("order_id", open_shop_uuid);//订单ID（用户订单详情页实际看到的订单号）
        requestParam.put("type", "1");//1:订单，2:券码

        requestParam.put("session", "ab5d80236e1afb21e94cdacc64bf4ca4ffc6399e");
        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", generateSign(requestParam, "632cfc8411c582ab8251417b25116d4a8a6f35a2", "MD5"));
        //构造form
        JSONObject jsonObject = HttpUtils.sendPostByForm("https://openapi.dianping.com/router/order/query/info",generateParams(requestParam));
        System.out.println(jsonObject);
        //发起post请求
        /*return Request Post("https://openapi.dianping.com/router/tuangou/receipt/prepare")
                .bodyForm(form.build())
                .setHeader("Content-Type", ContentType.create("application/x-www-form-urlencoded","UTF-8").toString())
                .execute().returnContent().asString();*/
    }


    public static String generateParams(Map<String, String> params){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue())) {
                sb.append(entry.getKey()).append("=").append(entry.getValue().trim()).append("&");
            }
        }
        String str = sb.substring(0,sb.length()-1);
        return str;
    }

    public static String generateSign(Map<String, String> params, String appSecret, String signMethod) {
        // 第一步：参数排序
        List<String> keys = new ArrayList();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue())) {
                keys.add(entry.getKey());
            }
        }
        Collections.sort(keys);
        // 第二步：把所有参数名和参数值串在一起
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(appSecret)) {
            sb.append(appSecret);
        }
        for (String key : keys) {
            sb.append(key).append(params.get(key).trim());
        }
        if (StringUtils.isNotEmpty(appSecret)) {
            sb.append(appSecret);
        }
        String encryptionKey = sb.toString().trim();
        // 第三步：加签
        if (signMethod.equals("MD5")) {
            try {
                String sign = genMd5(encryptionKey);
                return sign;
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }else{
            //开发者暂不需支持，支持MD5即可
            return "";
        }
    }

    public static String genMd5(String info) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] infoBytes = info.getBytes();
        md5.update(infoBytes);
        byte[] sign = md5.digest();
        return byteArrayToHex(sign);
    }

    public static String byteArrayToHex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toLowerCase());
        }
        return sign.toString();
    }
}
